package com.tramp.controller;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tramp.basic.entity.Demo;
import com.tramp.basic.service.DemoService;
import com.tramp.frame.server.base.BaseController;
import com.tramp.frame.server.base.ResultData;
import com.tramp.frame.server.base.field.DemoField;
import com.tramp.frame.server.exception.GenericException;

/**
 * @author chenjm1
 * @since 2017/10/20
 */
@RestController
@RequestMapping("/demo")
public class DemoController extends BaseController {

	@Autowired
	private DemoService demoService;

	@RequestMapping("/get")
	public ResultData get(String id) {
		Demo demo = demoService.get(id);
		return success(demo);
	}

	@RequestMapping("/insert")
	public ResultData insert(@RequestBody Demo demo) {
		demo = demoService.insert(demo);
		return success(demo);
	}

	@RequestMapping("/delete")
	public ResultData delete(String id) {
		demoService.delete(id);
		return success();
	}

	@RequestMapping("/update")
	public ResultData update(@RequestBody Demo demo) {
		demo = demoService.update(demo);
		return success(demo);
	}

	@RequestMapping("/updateField")
	public ResultData updateField(String id) {
		Demo demo = demoService.get(id);
		if (null == demo) {
			throw new GenericException("demo不存在");
		}
		Random random = new Random();
		demo.setName("updateField_" + random.nextInt(10));
		demo.setStatus(random.nextInt(3));
		demoService.updateField(demo, DemoField.update().name().status());
		return success(demoService.get(id));
	}

	/**
	 * 分页并统计（每次执行2条语句，一条select count语句，一条分页语句
	 *
	 * @return
	 */
	@RequestMapping("/pageCount")
	public ResultData pageCount() {
		this.setPageSqlId("DemoDao.listByEntity");
		List<Demo> list = demoService.listByEntity(new Demo());
		return successPage(list);
	}

	/**
	 * 只分页不统计(每次只执行分页语句)
	 *
	 * @return
	 */
	@RequestMapping("/page")
	public ResultData page() {
		this.setPageSqlId("DemoDao.listByEntity", false);
		List<Demo> list = demoService.listByEntity(new Demo());
		return successPage(list);
	}

	/**
	 * 自定义异常测试,返回json格式
	 * @return
	 */
	@RequestMapping("/genericException")
	public ResultData GenericException() {
		throw new GenericException("genericException测试");
	}

	@RequestMapping("/runtimeException")
	public ResultData runtimeException() {
		throw new RuntimeException("runtimeException测试");
	}
}
